﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NetSurveillance.WebApp.DataServices.Models;
using NetSurveillance.WebApp.Models;
using Resources;
using Newtonsoft.Json;
using NetSurveillance.WebApp.Exts;
namespace NetSurveillance.WebApp.Controllers
{
    public class HostController : BaseController
    {

        public ActionResult GetTreeNodes(string type)
        {
            List<Host> listHost = DataProvider.HostService.GetHostsByTaskId(CurrentTask.Id);
            if (listHost == null) return Json("error", JsonRequestBehavior.AllowGet);
            int tempIndex = 0;
            List<object> listObjects = new List<object>();
            foreach (var item in listHost.GroupBy(x => x.Mac, x => x))
            {
                tempIndex = tempIndex + 1;
                var obj = new { id = -tempIndex, pId = 0, name = item.Key };
                foreach (var host in item)
                {
                    bool @checked = false;
                    if (type == "monitor")
                    {
                        var qqMonitorHostModel = DataProvider.QQMonitorHostService.GetAllModels(false, p => p.HostId == host.Id && p.TaskId == CurrentTask.Id).FirstOrDefault();
                        if (qqMonitorHostModel != null && qqMonitorHostModel.StatusToken == 1)
                        {
                            @checked = true;
                        }
                    }
                    var objHost = new { id = host.Id, pId = -tempIndex, name = host.IP, @checked = @checked };
                    listObjects.Add(objHost);
                }
                listObjects.Add(obj);
            }
            return Json(JsonConvert.SerializeObject(listObjects), JsonRequestBehavior.AllowGet);
        }

        public ActionResult LoadImSearchMonitorList()
        {
            var ztreeNodes = new List<ZTreeNode>();
            List<Case> listCases = DataProvider.CaseService.GetAllModels(false).AsList();
            List<Task> listTasks = DataProvider.TaskService.GetAllModels(false).AsList();
            List<Host> listHosts = DataProvider.HostService.GetAllModels(false).AsList();
            foreach (var caseModel in listCases)
            {
                var caseNode = new ZTreeNode { Name = caseModel.Name, Id = caseModel.Id, IsParent = true };
                var caseNodeChilds = new List<ZTreeNode>();
                var currentTaskUnderCase = listTasks.Where<Task>(P => P.CaseId == caseModel.Id).AsList();
                foreach (var taskModel in currentTaskUnderCase)
                {
                    var taskNode = new ZTreeNode { Name = taskModel.Name, Id = taskModel.Id, ParentId = caseModel.Id };
                    var taskNodeChilds = new List<ZTreeNode>();
                    foreach (IGrouping<string, Host> hostModels in listHosts.Where<Host>(p => p.TaskId == taskModel.Id).GroupBy(p => p.Mac, p => p))
                    {
                        var hostGroupNode = new ZTreeNode { Name = hostModels.Key, ParentId = taskModel.Id };
                        var hostGroupNodes = new List<ZTreeNode>();
                        foreach (var hostModel in hostModels)
                        {
                            var hostNode = new ZTreeNode { Name = hostModel.IP, Id = hostModel.Id };
                            hostGroupNodes.Add(hostNode);
                        }
                        hostGroupNode.Children = hostGroupNodes;
                        taskNodeChilds.Add(hostGroupNode);
                    }
                    taskNode.Children = taskNodeChilds;
                    caseNodeChilds.Add(taskNode);
                }
                caseNode.Children = caseNodeChilds;
                ztreeNodes.Add(caseNode);
            }
            return Json(JsonConvert.SerializeObject(ztreeNodes));
        }

        public ActionResult InsertOrUpdateHostModel(string hostID)
        {
            if (!string.IsNullOrWhiteSpace(hostID))
            {
                long hostId;
                long.TryParse(hostID, out hostId);
                var hostModel = DataProvider.QQMonitorHostService.GetAllModels(true, p => p.HostId == hostId).FirstOrDefault() ?? new QQMonitorHost();
                if (hostModel.Id == 0 && hostModel.HostId == 0)
                {
                    hostModel.HostId = hostId;
                    var serviceResult = DataProvider.QQMonitorHostService.Save(hostModel);
                    return Json(serviceResult, JsonRequestBehavior.AllowGet);
                }
                if (hostModel.StatusToken == 1)
                {
                    hostModel.StatusToken = 0;
                    var serviceResult = DataProvider.QQMonitorHostService.UpdateOnly(hostModel, p => p.HostId, p => p.HostId == hostId);
                    return Json(serviceResult, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    hostModel.StatusToken = 1;
                    var serviceResult = DataProvider.QQMonitorHostService.UpdateOnly(hostModel, p => p.HostId, p => p.HostId == hostId);
                    return Json(serviceResult, JsonRequestBehavior.AllowGet);
                }
            }
            return Json("未选中一个主机项", JsonRequestBehavior.AllowGet);
        }


        public ActionResult LoadTaskUnderListHosts(long? taskid)
        {
            var hostModels = taskid.HasValue ? DataProvider.HostService.GetHostsByTaskId(taskid.Value) : new List<Host>();
            List<HostModel> lists = new List<HostModel>();
            if (hostModels.Count > 0)
            {
                foreach (var item in hostModels)
                {
                    HostModel hostModel = new HostModel { id = item.Id, HostName = item.HostName, IP = item.IP, Mac = item.Mac };
                    lists.Add(hostModel);
                }
            }
            return View(lists);
        }


        public ActionResult ChangeName()
        {
            if (!string.IsNullOrEmpty(Request["txt"]) & !string.IsNullOrEmpty(Request["hostId"]))
            {
                var hostid = long.Parse(Request["hostId"]);
                var host = DataProvider.HostService.GetModelById(hostid);
                if (host != null)
                    host.HostName = Request["txt"];
                DataProvider.HostService.Save(host);
            }
            else
            {
                ModelState.AddModelError("Error", MessageResource.Save_Error);
            }
            return RedirectToAction("LoadTaskUnderListHosts", new { taskid = 1 });
        }

        [HttpPost]
        public ActionResult Rename(long hostId, string hostName)
        {
            if (hostId == 0 || string.IsNullOrWhiteSpace(hostName))
                return CamelCaseJson(new AjaxResult(false, "Argument can't be null."));
            var host = DataProvider.HostService.GetModelById(hostId);
            if (host == null)
                return CamelCaseJson(new AjaxResult(false, "Can't find the host in db."));
            host.HostName = hostName;
            host.LastModifiedTime = DateTime.Now;
            var serviceResult = DataProvider.HostService.Save(host);
            return
                CamelCaseJson(serviceResult.ExecutedSuccess
                                  ? AjaxResult.TrueResult
                                  : new AjaxResult(false, MessageResource.Save_Error));
        }
    }
}
